package com.fsj.admin.system.controller;

import com.fsj.admin.common.config.Constant;
import com.fsj.admin.common.controller.BaseController;
import com.fsj.admin.common.domain.DictDO;
import com.fsj.admin.common.service.DictService;
import com.fsj.admin.common.utils.PageUtils;
import com.fsj.admin.common.utils.Query;
import com.fsj.admin.common.utils.R;
import com.fsj.admin.common.utils.TimeUtils;
import com.fsj.admin.system.domain.*;
import com.fsj.admin.system.service.*;
import com.fsj.admin.system.vo.InviteWaterVO;
import com.fsj.admin.system.vo.OrderWalletRecordsVO;
import com.fsj.admin.system.vo.UserChildsVO;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.joda.time.DateTimeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/sys/statis")
@Controller
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = {RuntimeException.class, Exception.class})
public class StatisticsController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(StatisticsController.class);

    String prefix = "system";
    @Autowired
    TUserService tUserService;
    @Autowired
    IdentityInfoService identityInfoService;
    @Autowired
    WalletService walletService;
    @Autowired
    CashRecordService cashRecordService;
    @Autowired
    ShopService shopService;
    @Autowired
    RescissionService rescissionService;
    @Autowired
    OrderService orderService;
    @Autowired
    InvitationRecordService invitationRecordService;
    @Autowired
    WalletRecordsService walletRecordsService;
    @Autowired
    DictService dictService;
    @Autowired
    UserService userService;
    @Autowired
    ShopWalletRecordsService shopWalletRecordsService;
    @Autowired
    ShopWalletService shopWalletService;
    @Autowired
    ShopCashRecordService shopCashRecordService;

    @RequiresPermissions("sys:statis:userChild")
    @GetMapping("/userChild")
    String userChild() {
        return prefix + "/statis/userChild";
    }

    @RequiresPermissions("sys:statis:userChild")
    @GetMapping("/userChildList")
    @ResponseBody()
    PageUtils orderList(@RequestParam Map<String, Object> params) {
        Query query = new Query(params);
        TUserDO tUserDO = tUserService.getUserByUserName(getUsername());
        if (tUserDO != null) {
            query.put("userId", tUserDO.getId());
            List<UserChildsVO> userChilds = tUserService.getUserChilds(query);

            int total = tUserService.countUserChilds(query);
            PageUtils pageUtils = new PageUtils(userChilds, total);
            return pageUtils;
        }
        return null;
    }


    @RequiresPermissions("sys:statis:userChild")
    @GetMapping("/shopChild")
    String shopChild() {
        return prefix + "/statis/shopChild";
    }

    @RequiresPermissions("sys:statis:userChild")
    @GetMapping("/shopChildList")
    @ResponseBody()
    List<UserChildsVO> shopChildList() {
        TUserDO tUserDO = tUserService.getUserByUserName(getUsername());
        if (tUserDO != null) {
            Map<String, Object> query = new HashMap<>(1);
            query.put("userId", tUserDO.getId());
            return tUserService.getShopChilds(query);
        }
        return null;
    }


    /**
     * 我的收益
     *
     * @return
     */
    @RequiresPermissions("sys:statis:userStatis")
    @GetMapping("/userStatis")
    String userStatis() {
        return prefix + "/statis/userStatis";
    }

    @RequiresPermissions("sys:statis:userStatis")
    @GetMapping("/userShopStatis")
    String userShopStatis() {
        return prefix + "/statis/userShopStatis";
    }

    @RequiresPermissions("sys:statis:userStatis")
    @GetMapping("/userStatisList")
    @ResponseBody()
    PageUtils userStatisList(@RequestParam Map<String, Object> params) {
        Query query = new Query(params);
        TUserDO tUserDO = tUserService.getUserByUserName(getUsername());
        if (tUserDO != null) {
            // userId type
            query.put("userId", tUserDO.getId());
            List<InviteWaterVO> inviteWater = tUserService.getInviteWater(query);
            int total = tUserService.countInviteWater(query);
            PageUtils pageUtils = new PageUtils(inviteWater, total);
            return pageUtils;
        }
        return null;
    }

    /**
     * 商家查看订单
     *
     * @return
     */
    @RequiresPermissions("sys:statis:orderStatis")
    @GetMapping("/orderStatis")
    String orderStatis() {
        return prefix + "/statis/orderStatis";
    }

    @RequiresPermissions("sys:statis:orderStatis")
    @GetMapping("/orderStatisList")
    @ResponseBody()
    PageUtils orderStatisList(@RequestParam Map<String, Object> params) {
        Query query = new Query(params);

        UserDO userDO = userService.get(getUserId());
        if (userDO.getRoleIds().toString().contains("61")) {
            ShopDO shop = shopService.getShopByShopMobile(getUsername());
            if (shop != null) {
                query.put("shopId", shop.getId());
            } else {
                return null;
            }
        }
        List<OrderWalletRecordsVO> list = shopWalletRecordsService.orderRecordsByShopId(query);
        int total = shopWalletRecordsService.countOrderRecords(query);
        PageUtils pageUtils = new PageUtils(list, total);
        return pageUtils;
    }


    /**
     * 首页统计
     *
     * @return
     */
    @RequiresPermissions("sys:statis:orderStatis")
    @PostMapping("/getStatis")
    @ResponseBody()
    R getStatis() {
        Map<String, Object> params = new HashMap<>();
        UserDO userDO = userService.get(getUserId());

        params.put("starDate", TimeUtils.getTodayStar(new Date()));
        params.put("endDate", TimeUtils.getTodayEnd(new Date()));
        if (userDO.getRoleIds().toString().contains("61")) {
            ShopDO shop = shopService.getShopByShopMobile(getUsername());

            params.put("privateKey", shop.getPrivateKey());
            if (shop != null) {
                params.put("shopId", shop.getId());
                //可用余额及冻结余额
                List<ShopWalletDO> list = shopWalletService.list(params);
                if (CollectionUtils.isEmpty(list)) {
                    params.put("amount", 0);
                    params.put("frozen", 0);
                } else {
                    params.put("amount", list.get(0).getAmount());
                    params.put("frozen", list.get(0).getCashFrozen().add(list.get(0).getSysFrozenAmout()));
                }
                // 今日订单 及 收入
                Map<String, Object> params1 = new HashMap<>();
                params1.put("shopId", shop.getId());
                OrderWalletRecordsVO todayStatis = shopWalletRecordsService.getShopStatis(params);
                params.put("todayOrderCount", todayStatis == null ? 0 : todayStatis.getId());
                params.put("todayOrderAmount", todayStatis == null ? 0 : todayStatis.getAmount());
                // 总订单及收入
                OrderWalletRecordsVO totalStatis = shopWalletRecordsService.getShopStatis(params1);
                params.put("totalOrderCount", totalStatis == null ? 0 : totalStatis.getId());
                params.put("totalOrderAmount", totalStatis == null ? 0 : totalStatis.getAmount());
            } else {
                return null;
            }
        } else {
            // 今日订单 及 收入
            OrderWalletRecordsVO todayStatis = shopWalletRecordsService.getSysStatis(params);
            params.put("todayOrderCount", todayStatis == null ? 0 : todayStatis.getId());
            params.put("todayOrderAmount", todayStatis == null ? 0 : todayStatis.getAmount());
            // 总订单及收入
            OrderWalletRecordsVO totalStatis = shopWalletRecordsService.getSysStatis(null);
            params.put("totalOrderCount", totalStatis == null ? 0 : totalStatis.getId());
            params.put("totalOrderAmount", totalStatis == null ? 0 : totalStatis.getAmount());

            params.put("amount", 0);
            params.put("frozen", 0);
        }

        return R.ok(params);
    }

    /**
     * 首页报表 按天统计订单及收入
     *
     * @return
     */
    @RequiresPermissions("sys:statis:orderStatis")
    @PostMapping("/getStatisByDay")
    @ResponseBody()
    R getStatisByDay(@RequestParam Integer days) {
        Map<String, Object> params = new HashMap<>();
        UserDO userDO = userService.get(getUserId());

        List<String> dateLists = TimeUtils.getLastDayDate(new Date(), days);
        if (CollectionUtils.isEmpty(dateLists)) {
            return R.error("暂无天数");
        }
        params.put("dataList", dateLists);
        if (userDO.getRoleIds().toString().contains("61")) {
            ShopDO shop = shopService.getShopByShopMobile(getUsername());
            if (shop != null) {
                params.put("shopId", shop.getId());
                // 今日订单 及 收入
                List<OrderWalletRecordsVO> listVo = shopWalletRecordsService.getStatisByDay(params);
                params.put("list", listVo);
            } else {
                return null;
            }
        }

        return R.ok(params);
    }


    /**
     * 商家查看API接口文档
     *
     * @return
     */
    @RequiresPermissions("sys:statis:orderStatis")
    @GetMapping("/showApi")
    String showApi() {
        return prefix + "/statis/dfb";
    }

    /**
     * 商家提现页面
     *
     * @return
     */
    @RequiresPermissions("sys:statis:shopCash")
    @GetMapping("/shopCash")
    String shopCash() {
        return prefix + "/statis/cash";
    }

    /**
     * 商家提现
     *
     * @return
     */
    @RequiresPermissions("sys:statis:shopCash")
    @PostMapping("/updateShopCash")
    @ResponseBody()
    R updateShopCash(ShopCashRecordDO shopCashRecordDO) {
        if (shopCashRecordDO.getCashAmount() == null || StringUtils.isBlank(shopCashRecordDO.getPayWay())) {
            return R.error("信息不完整");
        }

        if (shopCashRecordDO.getCashAmount().compareTo(new BigDecimal(0)) <= 0) {
            return R.error("提现金额过小");
        }

        List<DictDO> dictDOS = dictService.listByType(Constant.USER_CASH_MIN);
        if (CollectionUtils.isEmpty(dictDOS) || StringUtils.isBlank(dictDOS.get(0).getValue())) {
            return R.error("系统配置有误，请联系管理员");
        }
        if (shopCashRecordDO.getCashAmount().compareTo(new BigDecimal(dictDOS.get(0).getValue())) < 0) {
            return R.error("系统配置最小提现金额" + new BigDecimal(dictDOS.get(0).getValue()));
        }

        ShopDO shop = shopService.getShopByShopMobile(getUsername());
        if (shop == null) {
            return R.error("商家信息获取失败");
        }

        Map<String, Object> params = new HashMap<>(1);
        params.put("shopId", shop.getId());
        List<ShopWalletDO> list = shopWalletService.list(params);
        if (CollectionUtils.isEmpty(list)) {
            return R.error("商家钱包获取失败");
        }

        // 判断商家支付方式信息是否完整
        if (Constant.GENERAL_ONE.equals(shopCashRecordDO.getPayWay())) {
            if (StringUtils.isBlank(shop.getAlipayCode())) {
                return R.error("未上传支付宝收款码");
            }
            shopCashRecordDO.setPayCode(shop.getAlipayCode());
        } else if (Constant.GENERAL_TWO.equals(shopCashRecordDO.getPayWay())) {
            if (StringUtils.isBlank(shop.getVxPayCode())) {
                return R.error("未上传微信收款码");
            }
            shopCashRecordDO.setPayCode(shop.getVxPayCode());
        } else if (Constant.GENERAL_THREE.equals(shopCashRecordDO.getPayWay())) {
            if (StringUtils.isBlank(shop.getTenPayCode())) {
                return R.error("未上传腾讯收款码");
            }
            shopCashRecordDO.setPayCode(shop.getTenPayCode());
        } else if (Constant.GENERAL_FOUR.equals(shopCashRecordDO.getPayWay())) {
            if (StringUtils.isBlank(shop.getBankNo())) {
                return R.error("未上传银行卡信息");
            }
            shopCashRecordDO.setBankNo(shop.getBankNo());
            shopCashRecordDO.setBankName(shop.getBankName());
        } else {
            return R.error("支付方式不匹配");
        }

        ShopWalletDO shopWalletDO = list.get(0);
        if (shopCashRecordDO.getCashAmount().compareTo(shopWalletDO.getAmount()) > 0) {
            return R.error("余额不足，提现失败");
        }

        shopCashRecordDO.setLastAmount(shopWalletDO.getAmount());
        shopCashRecordDO.setStatus(Constant.GENERAL_ZERO);
        shopCashRecordDO.setShopId(shop.getId());
        shopCashRecordDO.setShopName(shop.getShopName());

        // 冻结提现金额
        shopWalletDO.setAmount(shopWalletDO.getAmount().subtract(shopCashRecordDO.getCashAmount()));
        shopWalletDO.setCashFrozen(shopWalletDO.getCashFrozen().add(shopCashRecordDO.getCashAmount()));
        int i = shopWalletService.update(shopWalletDO);
        if (i > 0) {
            shopCashRecordService.save(shopCashRecordDO);
        }

        return R.ok("申请成功，正在审核中..");
    }

}
